package main

import (
	"fmt"
	"os"
	"sanguo/node/moniter"
	"strings"

	"github.com/sniperHW/kendynet"
)

func gen_write(out_path, str string) {
	f, err := os.OpenFile(out_path, os.O_RDWR, os.ModePerm)
	if err != nil {
		if os.IsNotExist(err) {
			f, err = os.Create(out_path)
			if err != nil {
				kendynet.Errorf("create %s failed:%s", out_path, err.Error())
				return
			}
		} else {
			kendynet.Errorf("open %s failed:%s", out_path, err.Error())
			return
		}
	}

	err = os.Truncate(out_path, 0)

	_, err = f.WriteString(str)

	if nil != err {
		kendynet.Errorf("%s Write error:%s\n", out_path, err.Error())
	} else {
		kendynet.Infof("%s Write ok\n", out_path)
	}

	f.Close()
}

func gen_html(out_path string) {

	htmlStr := `
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <script src="js/jquery-3.3.1.js"></script>
    <script src="js/echarts.min.js"></script>
    <title>Title</title>
    <style>
        * {
            padding: 0;
            margin: 1%;
            list-style: none;
        }
        label{
            font-size: 12px;
        }
		#SC>div{
            float: left;
            width: 30%;
            height:300px;
        }
    </style>
	<script class ="json_" src="info.json"></script>
</head>
<body> 
 	<div>
       <label for="setTime">刷新时间(单位/s) <input type="text" id="setTime" name="seTime"></label>
        <button type="button" id="yes">确定</button>
    </div>
	<div id="SC">  
`
	divStr := ""
	scriptStr := `
	function draw(){`

	for key, field := range moniter.Message {
		divStr += fmt.Sprintf(`
		<div id="%s"`, key) + ` style="width: 30%;height:300px;"></div>`
		scriptStr += fmt.Sprintf(`
		var %s_Chart = echarts.init(document.getElementById('%s'));
	    %s_option = {
	        title: {text: '%s'},
			tooltip: {trigger: 'axis'},`, key, key, key, key)
		names := ""
		dataStr := ""
		for _, name := range field {
			_name := strings.Split(name, "transaction")
			names += fmt.Sprintf("'%s',", _name[1])
			dataStr += fmt.Sprintf(`
				{name:'%s',type:'line',data:data.%s},`, _name[1], name)
		}
		scriptStr += fmt.Sprintf(`
			legend: {data:[%s]},`, names) + `
	        grid: {left: '3%',right: '4%',bottom: '3%',containLabel: true},
	        xAxis: {type: 'category',boundaryGap: false,data: ['1','2','3','4','5','6','7']},
	        yAxis: {type: 'value'},
	        series: [`
		scriptStr += fmt.Sprintf(`%s
			]	
    	};
    	%s_Chart.setOption(%s_option);
		`, dataStr, key, key)
	}

	htmlStr += divStr + `
	</div>`
	htmlStr += `
</body>
<script src="info.json"></script>
<script>
	var timeInterval = 1
	var timer
	
	function setTimeInterval(){
		$.ajax({
			url:'http://127.0.0.1:10001/SetTime',
			type:'POST',
			data:{
				TimeInterval:timeInterval,
			},
			dataType:'json',
		})
		
	}

	timer = setInterval(function(){
    	RefreshJson();
		var oS=document.querySelector('.json_');
        document.head.removeChild(oS);//调用完删除在showSC函数里创建的script标签
	},timeInterval * 1000)	
	
	var btn = document.getElementById('yes');
    btn.addEventListener('click',
        function () {
            var setTime = document.getElementById('setTime');
            var time = parseInt(setTime.value);
            console.log(time);
			timeInterval = time
			setTimeInterval() 
	        clearInterval(timer); //每次先清除前面设置的定时器
	        timer = setInterval(function () {
	            RefreshJson();
	            var oS=document.querySelector('.json_');
	            document.head.removeChild(oS);//调用完删除在showSC函数里创建的script标签
	        },time*1000); //单位是s
			
        }
    );
	
	function RefreshJson(){
		var oS=document.createElement('script');
		oS.className = 'json_';
        oS.src='info.json';
        document.head.appendChild(oS);
        setTimeout(draw,1000);
		draw()
	}`
	htmlStr += scriptStr
	htmlStr += `
	}
</script>
</html>`

	gen_write(out_path, htmlStr)
}

func main() {
	gen_html("../html/index.html")
}
